<template>
  <script id="container" name="content" type="text/plain"></script>
</template>

<script>
import {postMedia} from '../../utils/api.js';
import Tools from '../../utils/tools.js';

function singleupload() {
  UE.plugin.register('singleupload', function () {
    let me       = this,
        url      = 'http://test.c.open.163.com/photo/upload.do',
        isLoaded = false,
        containerBtn;
    
    function initUploadBtn() {
      let w         = containerBtn.offsetWidth || 20,
          h         = containerBtn.offsetHeight || 20,
          btnIframe = document.createElement('iframe'),
          btnStyle  = 'display:block;width:' + w + 'px;height:' + h + 'px;overflow:hidden;border:0;margin:0;padding:0;position:absolute;top:0;left:0;filter:alpha(opacity=0);-moz-opacity:0;-khtml-opacity: 0;opacity: 0;cursor:pointer;';
      
      UE.dom.domUtils.on(btnIframe, 'load', function () {
        
        let timestrap = (+new Date()).toString(36),
            wrapper,
            btnIframeDoc,
            btnIframeBody;
        
        btnIframeDoc = (btnIframe.contentDocument || btnIframe.contentWindow.document);
        btnIframeBody = btnIframeDoc.body;
        wrapper = btnIframeDoc.createElement('div');
        
        wrapper.innerHTML = '<form id="edui_form_' + timestrap + '" style="' + btnStyle + '">' +
          '<input id="edui_input_' + timestrap + '" type="file" accept="image/png,image/jpeg,image/gif" name="' + 'imageFile' + '" ' +
          'style="' + btnStyle + '">' +
          '</form>';
        
        wrapper.className = 'edui-' + UE.Editor.ME.options.theme;
        // wrapper.id = UE.Editor.ME.ui.id + '_iframeupload';
        btnIframeBody.style.cssText = btnStyle;
        btnIframeBody.style.width = w + 'px';
        btnIframeBody.style.height = h + 'px';
        btnIframeBody.appendChild(wrapper);
        
        if (btnIframeBody.parentNode) {
          btnIframeBody.parentNode.style.width = w + 'px';
          btnIframeBody.parentNode.style.height = w + 'px';
        }
        
        let form = btnIframeDoc.getElementById('edui_form_' + timestrap);
        let input = btnIframeDoc.getElementById('edui_input_' + timestrap);
        
        UE.dom.domUtils.on(input, 'change', function () {
          if (!input.value) return;
          let loadingId = 'loading_' + (+new Date()).toString(36);
          let params = UE.utils.serializeParam(me.queryCommandValue('serverparam')) || '';
          
          let imageActionUrl = UE.Editor.ME.getActionUrl(me.getOpt('imageActionName'));
          let allowFiles = UE.Editor.ME.getOpt('imageAllowFiles');
          
          UE.Editor.ME.focus();
          UE.Editor.ME.execCommand('inserthtml', '<img class="loadingclass" id="' + loadingId + '" src="' + UE.Editor.ME.options.themePath + UE.Editor.ME.options.theme + '/images/spacer.gif" title="' + (me.getLang('simpleupload.loading') || '') + '" >');
          
          function callback(data) {
            try {
              let link, json, loader;
              json = data;
              link = json.data;
              if (json.message == 'success' && json.data) {
                loader = UE.Editor.ME.document.getElementById(loadingId);
                loader.onload = () => {
                  if (loader.width > 480) {
                    loader.width = '480'
                  }
                };
                loader.setAttribute('title', '');
                loader.setAttribute('src', link);
                loader.setAttribute('_src', link);
                loader.setAttribute('data-src', link);
                Tools.getImgSize(link).then(({height,width})=>{
                  loader.setAttribute('data-size',`${width}x${height}`)
                });
                loader.removeAttribute('alt');
                loader.removeAttribute('id');
                UE.dom.domUtils.removeClasses(loader, 'loadingclass');
              }
              else {
                showErrorLoader && showErrorLoader(json.state);
              }
            } catch (er) {
              console.log(er);
              showErrorLoader && showErrorLoader(me.getLang('simpleupload.loadError'));
            }
          }
          
          function showErrorLoader(title) {
            if (loadingId) {
              let loader = UE.Editor.ME.document.getElementById(loadingId);
              loader && UE.dom.domUtils.remove(loader);
              UE.Editor.ME.fireEvent('showmessage', {
                'id': loadingId,
                'content': title,
                'type': 'error',
                'timeout': 4000
              });
            }
          }
          
          // 判断文件格式是否错误
          let filename = input.value,
              fileext  = filename ? filename.substr(filename.lastIndexOf('.')) : '';
          if (!fileext || (allowFiles && (allowFiles.join('') + '.').indexOf(fileext.toLowerCase() + '.') == -1)) {
            showErrorLoader(me.getLang('simpleupload.exceedTypeError'));
            return;
          }
          
          postMedia('uploadImg', form).then(callback)
        });
        
        let stateTimer;
        UE.Editor.ME.addListener('selectionchange', function () {
          clearTimeout(stateTimer);
          stateTimer = setTimeout(function () {
            try {
              let state = UE.Editor.ME.queryCommandState('singleupload');
              if (state == -1) {
                input.disabled = 'disabled';
              }
              else {
                input.disabled = false;
              }
            }
            catch (e) {

            }
          }, 400);
        });
        isLoaded = true;
      });
      
      btnIframe.style.cssText = btnStyle;
      containerBtn.appendChild(btnIframe);
    }
    
    return {
      bindEvents: {
        'ready': function () {
          //设置loading的样式
          UE.utils.cssRule('loading',
            '.loadingclass{display:inline-block;cursor:default;background: url(\'' + this.options.themePath + this.options.theme + '/images/loading.gif\') no-repeat center center transparent;border:1px solid #cccccc;margin-right:1px;height: 22px;width: 22px;}\n' +
            '.loaderrorclass{display:inline-block;cursor:default;background: url(\'' + this.options.themePath + this.options.theme + '/images/loaderror.png\') no-repeat center center transparent;border:1px solid #cccccc;margin-right:1px;height: 22px;width: 22px;' +
            '}',
            this.document);
        },
        /* 初始化简单上传按钮 */
        'singleuploadbtnready': function (type, container) {
          containerBtn = container;
          initUploadBtn();
          // UE.Editor.ME.afterConfigReady(initUploadBtn);
        }
      },
      outputRule: function (root) {
        UE.utils.each(root.getNodesByTagName('img'), function (n) {
          if (/\b(loaderrorclass)|(bloaderrorclass)\b/.test(n.getAttr('class'))) {
            n.parentNode.removeChild(n);
          }
        });
      },
      commands: {
        'singleupload': {
          queryCommandState: function () {
            return isLoaded ? 0 : -1;
          }
        }
      }
    }
  });
}

export default {
  name: 'inputEditor',
  props: ['value'],
  data() {
    return {
      editor: undefined
    };
  },
  mounted() {
    singleupload();
    this.editor = UE.getEditor('container');
    window.editor = this.editor;
    this.editor.addListener('ready', () => {
      try {
        this.editor.setContent(this.value || "");
        this.editor.body.addEventListener('blur', () => {
          this.$emit('input', this.editor.getContent());
        });
      }
      catch (e) {
        
      }
    });
    
    this.$watch('value', (content) => {
      this.editor.setContent(content || '');
    });
  },
  beforeDestroy() {
    this.editor.destroy();
  }
};
</script>

<style lang="less">
</style>